package com.tanxi521.tnlevel.listener;

import com.tanxi521.tnlevel.TnLevel;
import com.tanxi521.tnlevel.dao.SQLManager;
import com.tanxi521.tnlevel.pojo.PlayerLevel;
import com.tanxi521.tnlevel.utils.ConfigReader;
import com.tanxi521.tnlevel.utils.LevelCounter;
import me.clip.placeholderapi.PlaceholderAPI;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.world.WorldSaveEvent;
import org.bukkit.inventory.AnvilInventory;
import org.bukkit.inventory.ItemStack;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * {@code @Author:} i-xiaotian
 * {@code @Date:} 2022/3/13 9:07
 * {@code @EMAIL:} 1254806967@qq.com
 */
@SuppressWarnings("unused")
public class TnLevelListener implements Listener {

    public static LinkedHashMap<Integer, Long> levels = new LinkedHashMap<>();
    public static List<HashMap<Integer, Long>> totalExpList = new ArrayList<>();
    public static Map<String, Integer> expGet = new ConcurrentHashMap<>();

    @EventHandler
    public void playerJoinEvent(PlayerJoinEvent e) {
        Player player = e.getPlayer();
        SQLManager.insertPlayer(player);
        LevelCounter.countPlayerLevelByExp(player, 0);
    }

    @EventHandler
    public void onPlayerExit(PlayerQuitEvent e) {
        Player player = e.getPlayer();
        final String uuid = player.getUniqueId().toString();
        final PlayerLevel cache = LevelCounter.getCache(uuid);
        if (Objects.isNull(cache)) return;
        LevelCounter.updatePlayerData(cache);
        LevelCounter.removeCache(uuid);
    }

    @EventHandler
    public void onWorldSave(WorldSaveEvent e) {
        LevelCounter.saveAll();
    }

    @EventHandler(priority = EventPriority.HIGHEST)
    public void playerExpChangeEvent(PlayerExpChangeEvent e) {
        Player player = e.getPlayer();
        int amount = e.getAmount();
        final String name = player.getName();
        expGet.put(name, amount);
        e.setAmount(0);
        LevelCounter.countPlayerLevelByExp(player, amount);
        String s = PlaceholderAPI.setPlaceholders(
                e.getPlayer(),
                ConfigReader.getExpMessage().replace("&", "§"),
                Pattern.compile("%([^%]+)%")
        );
        if (ConfigReader.getIsSendMessage()) {
            player.spigot().sendMessage(ConfigReader.getMsgType(), new BaseComponent[]{new TextComponent(s)});
            TnLevel.getInstance().getLogger().info(name + "经验变更");
        }

    }

    @EventHandler
    public void enchantItemEvent(EnchantItemEvent e) {
        Player enchanter = e.getEnchanter();
        String playerName = enchanter.getName();
        Integer playerLevel = SQLManager.gerPlayerLevelByName(playerName).getPlayerLevel();
        int expLevelCost = e.getExpLevelCost();
        e.setExpLevelCost(0);
        int cost = 0;
        if (expLevelCost == 30) {
            cost = 3;
            playerLevel = playerLevel - cost;
        } else if (expLevelCost > 10 && expLevelCost <= 20) {
            cost = 2;
            playerLevel = playerLevel - cost;
        } else if (expLevelCost <= 10) {
            cost = 1;
            playerLevel = playerLevel - cost;
        }
        LevelCounter.countPlayerLevelByLevel(playerName, playerLevel, enchanter);
        e.getEnchanter().spigot().sendMessage(ConfigReader.getMsgType(),
                new BaseComponent[]{new TextComponent("§e[等级系统] 你因使用 §c§l附魔台 §e减少了 §c§l" + cost + " §e级")});
        // 1tick后设置等级,防止被附魔台扣减造成显示错误
        Integer finalPlayerLevel = playerLevel;
        Bukkit.getScheduler().runTaskLaterAsynchronously(TnLevel.getInstance(), () -> enchanter.setLevel(finalPlayerLevel), 1);
    }

    @EventHandler
    public void inventoryClickEvent(InventoryClickEvent e) {

        if (!(e.getClickedInventory() instanceof AnvilInventory)) return;
        Player player = (Player) e.getWhoClicked();
        if (e.getSlot() != 2 || e.getCurrentItem() == null || e.getCurrentItem().getType() == Material.AIR) return;

        AnvilInventory clickedInventory = (AnvilInventory) e.getClickedInventory();

        int repairCost = clickedInventory.getRepairCost();
        String playerName = player.getName();
        final UUID uniqueId = player.getUniqueId();
        final PlayerLevel cache = LevelCounter.getCache(uniqueId.toString());
        Integer playerLevel = cache.getPlayerLevel();
        int newLevel = playerLevel - repairCost;
        LevelCounter.countPlayerLevelByLevel(playerName, newLevel, player);
        Bukkit.getScheduler().runTaskLaterAsynchronously(TnLevel.getInstance(), () -> player.setLevel(newLevel), 1);
//        ItemStack item = clickedInventory.getItem(0);
//        ItemStack item1 = clickedInventory.getItem(1);
//        ItemStack item2 = e.getCurrentItem();
//
//        if (item == null || item1 == null) return;
//        ItemStack clone = item2.clone();
//        item2.setAmount(0);
//        e.setCancelled(true);
//        if (e.isShiftClick()) {
//            e.setResult(Event.Result.DENY);
//            player.getInventory().addItem(clone);
//        } else {
//            e.getWhoClicked().setItemOnCursor(clone);
//        }
//        item.setAmount(item.getAmount() - 1);
//        item1.setAmount(item1.getAmount() - 1);
//        if (item.getAmount() <= 0) clickedInventory.clear(0);
//        if (item1.getAmount() <= 0) clickedInventory.clear(1);

        player.spigot().sendMessage(ConfigReader.getMsgType(),
                new BaseComponent[]{new TextComponent("§e[等级系统] 你因使用 §c§l铁砧 §e减少了 §c§l" + repairCost + " §e级")});


    }


}
